import mavcrc

def parseMsg(buffer):
        '''
            parse msg based on the buffer
            will parse all of the possible msg

            consider a msg contains 0xfe?
            TODO return the trimmed data
            typedef struct __mavlink_message {
                uint16_t checksum; ///< sent at end of packet
                uint8_t magic;   ///< protocol magic marker
                uint8_t len;     ///< Length of payload
                uint8_t seq;     ///< Sequence of packet
                uint8_t sysid;   ///< ID of message sender system/aircraft
                uint8_t compid;  ///< ID of the message sender component
                uint8_t msgid;   ///< ID of message in payload
                uint64_t payload64[(MAVLINK_MAX_PAYLOAD_LEN+MAVLINK_NUM_CHECKSUM_BYTES+7)/8];
            }mavlink_message_t;
            
        '''
        bufferLastLen = len(buffer)
        validMsgs = []
        invalidMsgs = []
        headFound = False
        indexLack = False
        lastHeadIndex = 0
        bufferLen = len(buffer)
        key = -1
        lastTailIndex = -1 
        while True:
            key = key + 1 
            if(key>=bufferLen):
                break
            head = buffer[key]
            if head == chr(0xfe):
                msg={}
                headFound = True
                try:
                    msg['startIndex'] = key
                    msg['len']=ord(buffer[key+1])
                    if key+8+msg['len']>len(buffer):
                        raise IndexError()
                    msg['seq']=ord(buffer[key+2])
                    msg['sysid']=ord(buffer[key+3])
                    msg['compid']=ord(buffer[key+4])
                    msg['msgid']=ord(buffer[key+5])
                    msg['payload']=buffer[(key+6):(key+6+msg['len'])]
                    crcStr= buffer[(key+1):(key+6+msg['len'])]
                    crc   =  buffer[(key+6+msg['len']):(key+8+msg['len'])]
                    msg['crc'] = crc
                    crcExpect = crc_calculate(crcStr,msg['msgid'])
                    # print ":".join("{:02x}".format(ord(c)) for c in crcExpect)
                    if crcExpect == crc:
                        validMsgs.append(msg)
                        key = key+ 7 + msg['len']
                        lastTailIndex = key
                        # print 'valid msg'
                    else:
                        invalidMsgs.append(msg)
                        lastTailIndex = key+ 7 + msg['len']
                        # print "invalid msg"
                except IndexError:
                    indexLack = True
                    break          
        if headFound == False or indexLack == False : 
            buffer=''
        else:
            buffer=buffer[(lastTailIndex+1):len(buffer)]

        validMsgLen = 0
        for validMsg in validMsgs:
            validMsgLen = validMsgLen + validMsg['len']+8
        abandonedCount = bufferLastLen - len(buffer) - validMsgLen
        return validMsgs,abandonedCount